// BOM表单组件 - 用于新增/编辑/查看BOM信息
<script setup lang="ts">
// 导入所需的Vue组件和工具函数
import {ref, reactive, defineProps, defineEmits, watch} from 'vue'
import {ElMessage} from 'element-plus'
import type {FormInstance} from 'element-plus'
// 导入相关类型定义和API
import {BomForm, BomMaterialDto, BomProcessDto,ProcessItem,MaterialItem} from '@/api/bom/type'
import {addApi, editApi,getBomDetailByIdApi} from '@/api/bom'
import {Plus} from '@element-plus/icons-vue'


// 物料和工序选择对话框
import MaterialDialog from '@/views/baseInfo/material/materialDialog/index.vue'
import ProcessDialog from '@/views/baseInfo/process/processDialog/index.vue'



// 物料选择弹框组件实例
const materialDialogRef = ref()

// 工序选择弹框组件实例
const processDialogRef = ref()

// 定义组件属性
const props = defineProps<{
  bomId?: number // BOM ID，编辑时传入
  mode: string // 组件模式：add/edit/view
}>()

// 定义组件事件
const emit = defineEmits(['save-success', 'cancel'])

// 表单ref，用于表单验证
const formRef = ref<FormInstance>()

// 初始化表单数据
const formData = reactive<BomForm>({
  id: undefined,
  bomCode: undefined,  // bom编码
  bomName: undefined,  // bom名称
  unitName: undefined, // 单位
  specification: undefined,  // 规格
  brand: undefined,   // 品牌
  manufacturer: undefined,  // 生产厂家
  materialType: undefined,  // 材质
  unitWeight:  undefined,  // 米重(kg/m)
  unitArea:  undefined,  // 米面积(m²/m)
  totalWeight: undefined,  // 总重(kg/件)
  thickness: undefined, // 厚度(mm)
  materialTotalPrices: undefined,
  processTotalPrices: undefined,
  totalPrices: undefined,
  description: undefined,
  isActive: 0,
  bomMaterialDtoList: [] as BomMaterialDto[],
  bomProcessDtoList: [] as BomProcessDto[],
})

// 选择基础物料相关
const baseMaterialDialogRef = ref()
const openBaseMaterialSelect = () => {
  baseMaterialDialogRef.value.onShow()
}

// 处理基础物料选择，选择哪个物料就将哪个物料的信息带入表单
const handleBaseMaterialSelect = (material: any) => {
  // 将选中物料的信息带入表单
  formData.bomCode = material.materialCode
  formData.bomName = material.materialName
  formData.unitName = material.unitName
  formData.specification = material.specification
  formData.brand = material.brand
  formData.manufacturer = material.manufacturer
  formData.materialType = material.materialType
  formData.unitWeight = material.unitWeight
  formData.unitArea = material.unitArea
  formData.totalWeight = material.totalWeight
  formData.thickness = material.thickness
}

// 物料和工序选择相关的状态变量
const selectedMaterials = ref<MaterialItem[]>([]) // 已选物料
const selectedProcesses = ref<ProcessItem[]>([]) // 已选工序

// 表单校验规则
const rules = {
  bomCode: [{required: true, message: '请输入BOM编码', trigger: 'blur'}],
  bomName: [{required: true, message: '请输入BOM名称', trigger: 'blur'}],
}

// 打开物料选择弹窗组件
const openMaterialSelect = () => {
  materialDialogRef.value.onShow()
}

// 物料多选变化事件处理
const handleMaterialSelectionChange = (selection: MaterialItem[]) => {
  selectedMaterials.value = selection
}

// 确认物料选择,将选中的物料添加到BOM物料清单中
const confirmMaterialSelect = () => {
  console.log("物料选择框确认按钮，子传父触发")
  selectedMaterials.value.forEach((material) => {
    // 检查物料是否已存在于清单中
    const exists = formData.bomMaterialDtoList.some(
        (item) => item.materialId === material.id
    )
    if (!exists) {
      const purchasePrice = Number(material.purchasePrice) || 0
      // 添加新物料到清单
      formData.bomMaterialDtoList.push({
        id: undefined,
        bomId: formData.id,
        materialId: material.id,
        materialCode: material.materialCode,
        materialName: material.materialName,
        quantity: 1, // 默认数量为1
        unitId: material.unitId,
        unitName: material.unitName,
        specification: material.specification,
        purchasePrice: purchasePrice,
        cost: purchasePrice, // 初始成本等于单价
        description: '',

        brand: material.brand,  // 品牌
        manufacturer: material.manufacturer,  // 生产厂家
        materialType: material.materialType,  // 材质
        unitWeight: material.unitWeight,  // 米重(kg/m)
        unitArea: material.unitArea,  // 米面积(m²/m)
        totalWeight: material.totalWeight,  // 总重(kg/件)
        thickness:material.thickness, // 厚度(mm)
      })
    }
  })
  // 关闭物料选择弹窗组件
  materialDialogRef.value.onClose()
  calculateTotalPrices() // 重新计算总价
}

// 从物料清单中移除物料
const removeMaterial = (index: number) => {
  formData.bomMaterialDtoList.splice(index, 1)
  calculateTotalPrices() // 重新计算总价
}

// 计算单个物料的成本
const calculateMaterialCost = (row: MaterialItem) => {
  if (row.quantity && row.purchasePrice) {
    row.cost = Number(row.quantity) * Number(row.purchasePrice) // 成本 = 数量 * 单价
  } else {
    row.cost = 0
  }
  calculateTotalPrices() // 重新计算总价
}

// 工序相关方法
// 打开工序选择弹窗
const openProcessSelect = () => {
  processDialogRef.value.onShow()
}

// 工序多选变化事件处理
const handleProcessSelectionChange = (selection: ProcessItem[]) => {
  selectedProcesses.value = selection
}

// 确认工序选择,将选中的工序添加到BOM工序清单中
const confirmProcessSelect = () => {
  selectedProcesses.value.forEach((process) => {
    // 检查工序是否已存在于清单中
    const exists = formData.bomProcessDtoList.some(
        (item) => item.processId === process.id
    )
    if (!exists) {
      // 添加新工序到清单
      formData.bomProcessDtoList.push({
        id: undefined,
        bomId: formData.id,
        processId: process.id,
        processCode: process.processCode,
        processName: process.processName,
        cost: process.cost,
        description: '',
      })
    }
  })
  processDialogRef.value.onClose()
  calculateTotalPrices() // 重新计算总价
}

// 从工序清单中移除工序
const removeProcess = (index: number) => {
  formData.bomProcessDtoList.splice(index, 1)
  calculateTotalPrices() // 重新计算总价
}

// 处理提交数据,避免提交多余字段,并断开引用关系
const handleSubmitData = () => {
  const submitData = JSON.parse(JSON.stringify(formData)) // 深拷贝,断开引用

  // 处理物料清单数据
  submitData.bomMaterialDtoList = submitData.bomMaterialDtoList.map(
      (item: BomMaterialDto) => ({
        id: item.id,
        bomId: submitData.id,
        materialId: item.materialId,
        quantity: Number(item.quantity),
        unitId: item.unitId,
        cost: Number(item.cost),
        description: item.description || '',
      })
  )

  // 处理工序清单数据
  submitData.bomProcessDtoList = submitData.bomProcessDtoList.map(
      (item: BomProcessDto) => ({
        id: item.id,
        bomId: submitData.id,
        processId: item.processId,
        cost: Number(item.cost),
        description: item.description || '',
      })
  )
  return submitData
}

// 提交表单
const submitForm = async () => {
  if (props.mode === 'view') return // 查看模式不允许提交

  try {
    // 表单验证
    await formRef.value?.validate()
    // 验证是否选择了物料和工序
    if (formData.bomMaterialDtoList.length === 0) {
      ElMessage.warning('请选择物料')
      return
    }
    if (formData.bomProcessDtoList.length === 0) {
      ElMessage.warning('请选择工序')
      return
    }

    // 处理提交数据
    const submitData = handleSubmitData()
    console.log(props.mode+"提交数据："+submitData.value)
    if (props.mode === 'add') {
      // 调用保存API
      await addApi(submitData)
    }
    if (props.mode === 'edit') {
      // 调用保存API
      await editApi(submitData)
    }

    ElMessage.success('保存成功')
    emit('save-success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消操作
const cancel = () => {
  emit('cancel')
}

// 监听bomId变化,当编辑时加载BOM详情
watch(
    () => props.bomId,
    async (newVal) => {
      if (newVal) {
        try {
          const res = await getBomDetailByIdApi(newVal)
          if (res?.data) {
            Object.assign(formData, res.data) // 加载详情数据到表单
          }
        } catch (error) {
          console.error('获取BOM详情失败:', error)
        }
      }
    },
    {immediate: true}
)

// 计算所有价格
const calculateTotalPrices = () => {
  // 计算物料总价 = 所有物料成本之和
  const materialTotal = formData.bomMaterialDtoList.reduce((total, item) => {
    return total + (Number(item.cost) || 0)
  }, 0)
  formData.materialTotalPrices = materialTotal

  // 计算工序总价 = 所有工序成本之和
  const processTotal = formData.bomProcessDtoList.reduce((total, item) => {
    return total + (Number(item.cost) || 0)
  }, 0)
  formData.processTotalPrices = processTotal

  // 计算总价 = 物料总价 + 工序总价
  formData.totalPrices = materialTotal + processTotal
}

// 当前激活的tab页
const activeTab = ref('materials')

</script>

<template>
  <div class="bom-form">
    <div class="form-header">
      <h3>{{ mode === 'add' ? '新增BOM' : mode === 'edit' ? '编辑BOM' : 'BOM详情' }}</h3>
    </div>

    <el-form ref="formRef"
             :model="formData"
             :rules="rules"
             label-width="90px"
             :disabled="mode === 'view'">

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="物料编码" prop="bomCode" required>
            <el-input v-model="formData.bomCode" placeholder="请选择基础物料" readonly>
              <template #append>
                <el-button @click="openBaseMaterialSelect">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料名称" prop="bomName">
            <el-input v-model="formData.bomName" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单位">
            <el-input v-model="formData.unitName" readonly />
          </el-form-item>
        </el-col>
      </el-row>



      <!-- 物料基础信息 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="规格">
            <el-input v-model="formData.specification" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="品牌">
            <el-input v-model="formData.brand" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产厂家">
            <el-input v-model="formData.manufacturer" readonly />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="材质">
            <el-input v-model="formData.materialType" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="米重">
            <el-input v-model="formData.unitWeight" readonly>
              <template #append>kg/m</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="米面积">
            <el-input v-model="formData.unitArea" readonly>
              <template #append>m²/m</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="总重">
            <el-input v-model="formData.totalWeight" readonly>
              <template #append>kg/件</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="厚度">
            <el-input v-model="formData.thickness" readonly>
              <template #append>mm</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 价格信息 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="物料总价">
            <el-input v-model="formData.materialTotalPrices"
                      disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工序总价">
            <el-input v-model="formData.processTotalPrices"
                      disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总价">
            <el-input v-model="formData.totalPrices"
                      disabled>
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 使用tabs替换原来的两个表格 -->
      <el-tabs v-model="activeTab">
        <!-- 物料清单tab -->
        <el-tab-pane label="物料清单"
                     name="materials">
          <el-form-item prop="bomMaterialDtoList">
            <el-button type="primary"
                       @click="openMaterialSelect"
                       style="margin-bottom: 10px"
                       :icon="Plus">添加物料
            </el-button>
            <el-table :data="formData.bomMaterialDtoList"
                      border
                      style="width: 100%">
              <el-table-column type="index"
                               label="序号"
                               width="70" />
              <el-table-column prop="materialCode"
                               label="物料编码"
                               min-width="120" />
              <el-table-column prop="materialName"
                               label="物料名称"
                               min-width="120" />
              <el-table-column prop="specification"
                               label="规格"
                               min-width="120" />
              <el-table-column prop="quantity"
                               label="数量"
                               width="120">
                <template #default="scope">
                  <el-input-number v-model="scope.row.quantity"
                                   :min="1"
                                   :precision="0"
                                   style="width: 100px"
                                   @change="calculateMaterialCost(scope.row)" />
                </template>
              </el-table-column>
              <el-table-column prop="unitName"
                               label="单位"
                               width="80" />
              <el-table-column prop="purchasePrice"
                               label="单价"
                               width="120" />
              <el-table-column prop="cost"
                               label="成本"
                               width="120" />
              <el-table-column prop="brand" label="品牌" min-width="100" />
              <el-table-column prop="manufacturer" label="生产厂家" min-width="150" />
              <el-table-column prop="materialType" label="材质" min-width="100" />
              <el-table-column prop="unitWeight" label="米重(kg/m)" min-width="100" />
              <el-table-column prop="unitArea" label="面积(m²/m)" min-width="100" />
              <el-table-column prop="totalWeight" label="总重(kg/件)" min-width="100" />
              <el-table-column prop="thickness" label="厚度(mm)" min-width="100" />

              <el-table-column label="操作"
                               width="80">
                <template #default="scope">
                  <el-button type="danger"
                             link
                             @click="removeMaterial(scope.$index)"
                             icon="Delete" />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-tab-pane>
        <!-- 工序清单tab -->
        <el-tab-pane label="工序清单"
                     name="processes">
          <el-form-item prop="bomProcessDtoList">
            <el-button type="primary"
                       @click="openProcessSelect"
                       style="margin-bottom: 10px"
                       :icon="Plus">添加工序
            </el-button>
            <el-table :data="formData.bomProcessDtoList"
                      border
                      style="width: 100%">
              <el-table-column type="index"
                               label="序号"
                               width="70" />
              <el-table-column prop="processCode"
                               label="工序编码"
                               min-width="120" />
              <el-table-column prop="processName"
                               label="工序名称"
                               min-width="120" />
              <el-table-column prop="cost"
                               label="成本"
                               width="120" />
              <el-table-column label="操作"
                               width="80">
                <template #default="scope">
                  <el-button type="danger"
                             link
                             @click="removeProcess(scope.$index)"
                             icon="Delete" />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <el-form-item label="描述">
        <el-input v-model="formData.description"
                  type="textarea"
                  :rows="3"
                  placeholder="输入描述" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="formData.isActive">
          <el-radio :value="0">启用</el-radio>
          <el-radio :value="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <div class="form-actions">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary"
                 @click="submitForm"
                 v-if="mode !== 'view'">保存
      </el-button>
    </div>

    <!--选择物料 弹框组件-->
    <material-dialog ref="materialDialogRef" @handleMaterialSelectionChange="handleMaterialSelectionChange" @confirm-material-select="confirmMaterialSelect"/>

    <!--选择工序弹框组件-->
    <process-dialog ref="processDialogRef"
                    @handleProcessSelectionChange="handleProcessSelectionChange"
                    @confirmProcessSelect="confirmProcessSelect"
    />

    <!-- 添加基础物料选择弹框 -->
    <material-dialog
      ref="baseMaterialDialogRef"
      :multiple="false"
      @handleMaterialSelect="handleBaseMaterialSelect"
    />

  </div>
</template>

<style scoped lang="scss">
.bom-form {
  padding: 20px;
  padding-top: 0;
  background: #fff;
  height: 100%;
  overflow-y: auto;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;

    h3 {
      margin: 0;
      font-size: 18px;
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;

  }

  // 修改禁用状态下的样式
  :deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: var(
            --el-input-disabled-bg-color,
            var(--el-disabled-bg-color)
    );
  }

  :deep(.el-input.is-disabled .el-input__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }

  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }

  :deep(.el-radio.is-disabled.is-checked) {
    .el-radio__label {
      color: var(--el-text-color-primary);
    }
  }

  :deep(.el-radio.is-disabled) {
    .el-radio__label {
      color: var(--el-text-color-primary);
    }
  }

  // 添加价格输入样式
  :deep(.el-input-group__append) {
    padding: 0 10px;
    background-color: var(--el-color-primary-light-8);
    color: var(--el-color-primary);
    font-weight: bold;
  }

  // 添加tabs相关样式
  :deep(.el-tabs__header) {
    margin-bottom: 15px;
  }

  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
  }

  :deep(.el-tabs__item) {
    font-size: 14px;
    height: 40px;
    line-height: 40px;
  }

  :deep(.el-tabs__item.is-active) {
    font-weight: bold;
  }
}
</style>
